//
//  HomeViewController.swift
//  MyWeiBo
//
//  Created by mac on 15/3/4.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class HomeViewController: BaseTableViewController {
    var statuses = [Status]()
    var currStatusRequest: StatusRequest?
    
    // MARK: 类的快速构造方法
    class func homeNavigationControllerWithTitle(title: String) -> WBNavigationController {
        let vc = controllerWithStoryBoardName("HomeViewController") as! WBNavigationController
        vc.topViewController.title = title
        return vc;
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        weak var wself = self

        self.tableView.addLegendHeaderWithRefreshingBlock { () -> Void in
            wself?.loadNewStatusData()
        }
        self.tableView.addLegendFooterWithRefreshingBlock { () -> Void in
            wself?.loadMoreStatusData()
        }
        self.tableView.legendHeader.beginRefreshing()
    }
    
    ///  加载更多数据,加载之前的微博
    func loadMoreStatusData() {
        let account = AccountTool.getAccountFromLoacl()
        if account == nil {
            NSNotificationCenter.defaultCenter().postNotificationName(WB_SwithcToOAuthController_Notification, object: nil)
        } else {
            weak var weakSelf = self
            if let request = self.currStatusRequest {
                request.max_id--
                StatusTool.requestStatusWithStatusRequest(request, complete: { (statues, error) -> () in
                    if error != nil {
                        SVProgressHUD.showErrorWithStatus("获取数据失败,请检查你的网络", maskType: .Gradient)
                    } else {
                        weakSelf?.loadImageCacheData(statues!)
                        weakSelf?.currStatusRequest = request
                        weakSelf?.tableView.legendFooter.endRefreshing()
                    }
                })
            }
        }
    }
    
    ///  加载最新数据
    func loadNewStatusData() {
        let account = AccountTool.getAccountFromLoacl()
        if account == nil {
            NSNotificationCenter.defaultCenter().postNotificationName(WB_SwithcToOAuthController_Notification, object: nil)
        } else {
            weak var weakSelf = self
            SVProgressHUD.show()
            let request = StatusRequest()
            request.access_token = account?.access_token
            currStatusRequest = request
            StatusTool.requestStatusWithStatusRequest(request, complete: { (statues, error) -> () in
                if error != nil {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showErrorWithStatus("获取数据失败,请检查你的网络", maskType: .Gradient)
                    weakSelf?.currStatusRequest = nil
                } else {
                    weakSelf?.loadImageCacheData(statues!, newUpDate: true)
                    weakSelf?.tableView.legendHeader.endRefreshing()
                }
            })
        }
    }
    
    // MARK: 缓存图片数据
    func loadImageCacheData(statues: Statuses, newUpDate: Bool = false) {
        weak var weakSelf = self
        ImageTool.saveImagesToLocalWithStatues(statues.statuses!)  { () -> () in
            if !newUpDate {
                self.statuses += statues.statuses!
            } else {
                self.statuses = statues.statuses!
            }

            if self.statuses.count > 0 {
                for item in self.statuses {
                    let cellID = HomeCell.cellIDWithStatus(item)
                    let cell = self.tableView.dequeueReusableCellWithIdentifier( cellID ) as! HomeCell
                    item.cellHeight = cell.cellHeightWithStatus(item)
                }
                weakSelf?.currStatusRequest?.max_id = Int64(self.statuses.last!.id)
            }
            SVProgressHUD.dismiss()
            weakSelf?.tableView.reloadData()
        }
    }
}

extension HomeViewController: UITableViewDelegate{
    // MARK: UITbaleViewDataSource
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses[indexPath.row]
        let cellID = HomeCell.cellIDWithStatus(status)
        let cell = tableView.dequeueReusableCellWithIdentifier( cellID ) as! HomeCell
        cell.status = status
        weak var weakSelf = self
        if cell.imageDidSelected == nil {
            cell.imageDidSelected = { (cell: HomeCell, photoIndex:Int ) -> () in
                let urls = cell.status?.statusPictureURL
                var photos = [Photo]()
                let smallImages = cell.photos!
                var i = 0
                for item in urls! {
                    let p = Photo(urlString: item.largeImage_pci!, placeHolderImage: smallImages[i])
                    photos.append(p)
                    i++
                }
                let vc = PhotoBrowserController.photoBrowserController(photos, selectedIndex: photoIndex)
                println(photoIndex)
                weakSelf?.presentViewController(vc, animated: false, completion: nil)
            }
        }
        return cell
    }
    
    // MARK: UITableViewDelegate
    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 400
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses[indexPath.row]
        return status.cellHeight
    }
}

